package com.yxs.sjbapp;

import android.content.Context;
import android.content.DialogInterface;
import android.app.Activity;
import android.app.AlertDialog;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.FilenameFilter;

public class Ysys {
    private Ysys() {}

    // Log level constants (匹配android.util.Log)
    public static final int VERBOSE = Log.VERBOSE;
    public static final int DEBUG = Log.DEBUG;
    public static final int INFO = Log.INFO;
    public static final int WARN = Log.WARN;
    public static final int ERROR = Log.ERROR;

    // Logging control flags
    private static boolean loggingEnabled = true;
    private static boolean fileLoggingEnabled = false;

    // File logging constants and variables
    private static final String LOG_DIR_NAME = "logs";
    private static final String LOG_FILE_PREFIX = "app_log_";
    private static final String LOG_FILE_EXT = ".txt";
    private static final int MAX_LOG_FILES = 7; // 保留最近7天的日志
    private static String logDirPath = null;

    // 日志写入线程池
    private static final ExecutorService logExecutor = Executors.newSingleThreadExecutor();

    /**
     * 显示退出确认对话框
     * @param activity 当前Activity
     */
    public static void ExitApp(final Activity activity) {
        if (activity == null || activity.isFinishing()) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("确认退出")
            .setMessage("确定要退出应用吗？")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    exitApp(activity);
                }
            })
            .setNegativeButton(android.R.string.no, null)
            .setCancelable(false)
            .show();
    }

    /**
     * 退出应用
     * @param activity 当前Activity
     */
    public static void exitApp(Activity activity) {
        if (activity != null) {
            log(INFO,"Lifecycle", "退出应用");
            shutdown();
            Ynet.shutdown();         
            activity.finishAffinity(); // 关闭所有Activity
        }
    }

    /**
     * 安全退出应用（完全结束进程）
     * @param activity 当前Activity
     */
    public static void exitAppCompletely(Activity activity) {
        if (activity != null) {
            log(INFO,"Lifecycle", "完全退出应用");
            shutdown();
            Ynet.shutdown();          
            activity.finishAffinity(); // 关闭所有Activity
            System.exit(0); // 完全退出进程
        }
    }

    /**
     * 启用文件日志功能
     * @param context 上下文对象
     */
    public static void enableFileLogging(Context context) {
        fileLoggingEnabled = true;
        logDirPath = getLogDirPath(context);
        cleanupOldLogs(); // 清理旧日志
    }

    /**
     * 禁用文件日志功能
     */
    public static void disableFileLogging() {
        fileLoggingEnabled = false;
    }

    /**
     * 启用/禁用所有日志
     */
    public static void setLoggingEnabled(boolean enabled) {
        loggingEnabled = enabled;
    }

    /**
     * 获取日志目录路径
     */
    private static String getLogDirPath(Context context) {
        // 使用应用的外部文件目录，这样用户可以通过文件管理器访问
        File logDir = new File(context.getExternalFilesDir(null), LOG_DIR_NAME);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        return logDir.getAbsolutePath();
    }

    /**
     * 清理旧日志文件
     */
    private static void cleanupOldLogs() {
        if (logDirPath == null) return;

        File logDir = new File(logDirPath);
        // 使用传统的文件过滤器替代 lambda 表达式
        File[] logFiles = logDir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.startsWith(LOG_FILE_PREFIX) && name.endsWith(LOG_FILE_EXT);
                }
            });

        if (logFiles != null && logFiles.length > MAX_LOG_FILES) {
            // 按修改时间排序，删除最旧的
            Arrays.sort(logFiles, new Comparator<File>() {
                    @Override
                    public int compare(File f1, File f2) {
                        return Long.compare(f1.lastModified(), f2.lastModified());
                    }
                });
            for (int i = 0; i < logFiles.length - MAX_LOG_FILES; i++) {
                logFiles[i].delete();
            }
        }
    }

    /**
     * 获取当前日志文件路径（按日期）
     */
    private static String getCurrentLogFilePath() {
        if (logDirPath == null) return null;

        String dateStr = new SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(new Date());
        return logDirPath + File.separator + LOG_FILE_PREFIX + dateStr + LOG_FILE_EXT;
    }

    /**
     * 将日志写入文件
     */
    private static void writeToFile(final String tag, final String message, final int level) {
        if (!fileLoggingEnabled || logDirPath == null) return;

        // 使用线程池执行文件操作
        logExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    String levelStr;
                    switch (level) {
                        case VERBOSE: levelStr = "V"; break;
                        case DEBUG: levelStr = "D"; break;
                        case INFO: levelStr = "I"; break;
                        case WARN: levelStr = "W"; break;
                        case ERROR: levelStr = "E"; break;
                        default: levelStr = "D"; break;
                    }

                    String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
                        .format(new Date());
                    String logEntry = String.format(Locale.getDefault(), 
                                                    "%s %s/%s: %s\n", timestamp, levelStr, tag, message);

                    String filePath = getCurrentLogFilePath();
                    if (filePath == null) return;

                    FileOutputStream fos = null;
                    OutputStreamWriter osw = null;

                    try {
                        fos = new FileOutputStream(filePath, true); // 追加模式
                        osw = new OutputStreamWriter(fos, "UTF-8");
                        osw.append(logEntry);
                        osw.flush();
                    } catch (IOException e) {
                        Log.e("Ysys", "写入日志文件失败: " + e.getMessage());
                        // 禁用文件日志以避免持续失败
                        fileLoggingEnabled = false;
                    } finally {
                        try {
                            if (osw != null) osw.close();
                        } catch (IOException e) {
                            Log.e("Ysys", "关闭输出流写入器失败: " + e.getMessage());
                        }
                        try {
                            if (fos != null) fos.close();
                        } catch (IOException e) {
                            Log.e("Ysys", "关闭文件输出流失败: " + e.getMessage());
                        }
                    }
                }
            });
    }

    /**
     * 记录日志（支持不同级别和文件记录）
     * @param level 日志级别
     * @param tag 日志标签
     * @param message 日志消息
     */
    public static void log(int level, String tag, String message) {
        if (!loggingEnabled) return;

        // 原有的 Logcat 输出
        switch (level) {
            case VERBOSE:
                Log.v(tag, message);
                break;
            case DEBUG:
                Log.d(tag, message);
                break;
            case INFO:
                Log.i(tag, message);
                break;
            case WARN:
                Log.w(tag, message);
                break;
            case ERROR:
                Log.e(tag, message);
                break;
            default:
                Log.d(tag, message);
                break;
        }

        // 写入文件
        writeToFile(tag, message, level);
    }

    /**
     * 简化版日志记录（使用DEBUG级别）
     * @param key 日志标签
     * @param value 日志消息
     */
    public static void log(String key, String value) {
        log(DEBUG, key, value);
    }

    /**
     * 记录Verbose级别日志
     */
    public static void v(String tag, String message) {
        log(VERBOSE, tag, message);
    }

    /**
     * 记录Debug级别日志
     */
    public static void d(String tag, String message) {
        log(DEBUG, tag, message);
    }

    /**
     * 记录Info级别日志
     */
    public static void i(String tag, String message) {
        log(INFO, tag, message);
    }

    /**
     * 记录Warn级别日志
     */
    public static void w(String tag, String message) {
        log(WARN, tag, message);
    }

    /**
     * 记录Error级别日志
     */
    public static void e(String tag, String message) {
        log(ERROR, tag, message);
    }

    /**
     * 记录Error级别日志（带异常）
     */
    public static void e(String tag, String message, Throwable tr) {
        if (!loggingEnabled) return;

        Log.e(tag, message, tr);

        // 将异常信息也写入文件
        if (fileLoggingEnabled) {
            String stackTrace = Log.getStackTraceString(tr);
            writeToFile(tag, message + "\n" + stackTrace, ERROR);
        }
    }

    /**
     * 获取所有日志文件列表
     * @param context 上下文
     * @return 日志文件数组
     */
    public static File[] getLogFiles(Context context) {
        File logDir = new File(context.getExternalFilesDir(null), LOG_DIR_NAME);
        if (logDir.exists() && logDir.isDirectory()) {
            return logDir.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        return name.startsWith(LOG_FILE_PREFIX) && name.endsWith(LOG_FILE_EXT);
                    }
                });
        }
        return new File[0];
    }

    /**
     * 清空所有日志文件
     * @param context 上下文
     */
    public static void clearAllLogs(Context context) {
        File[] logFiles = getLogFiles(context);
        for (File file : logFiles) {
            file.delete();
        }
    }

    /**
     * 关闭日志线程池（在应用退出时调用）
     */
    public static void shutdown() {
        logExecutor.shutdown();
    }
}
